package android.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import winkyle.woodenfish.android.exception.LoginException;
import winkyle.woodenfish.android.service.UserInfoService;
import winkyle.woodenfish.dao.UserInfoDao;
import winkyle.woodenfish.enums.ResultEnum;
import winkyle.woodenfish.model.dto.UserDto;
import winkyle.woodenfish.model.po.UserInfo;
import winkyle.woodenfish.util.FileStoreUtil;

import java.util.List;

/**
 * @author winkyle
 * @date 2018/06/22
 * @description 用户信息业务接口层的实现类
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

	@Autowired
	private UserInfoDao userInfoDao;

	@Override
	public UserDto verifyAccount(String account, String password) {
		List<UserInfo> userInfos = userInfoDao.findByAccount(account);
		if (userInfos == null || userInfos.isEmpty()) {
			throw new LoginException(ResultEnum.USERNOEXIST);
		}
		if (!password.equals(userInfos.get(0).getPassword())) {
			throw new LoginException(ResultEnum.PASSWORDWRONG);
		}
		UserDto userDto = new UserDto();
		userDto.setUserId(userInfos.get(0).getUserId());
		return userDto;
	}

	@Override
	public UserDto findUserInfoByUserId(String userId) {
		UserInfo userInfo = userInfoDao.findOne(userId);
		UserDto userDto = new UserDto();
		userDto.setAccount(userInfo.getAccount());
		userDto.setBirthday(userInfo.getBirthday());
		userDto.setCompany(userInfo.getCompany());
		userDto.setHeadPortrait(userInfo.getHeadPortrait());
		userDto.setNick(userInfo.getNick());
		userDto.setPost(userInfo.getPost());
		userDto.setSex(userInfo.getSex());
		userDto.setUserId(userInfo.getUserId());
		return userDto;
	}

	@Override
	public String modifyHeadPortraitByUserId(String userId, String path, MultipartFile headPortrait){
		if (headPortrait==null||headPortrait.isEmpty()) {
			return null;
		}
		String headPortraitUrl = "file/headPortrait/";
		String filePath = FileStoreUtil.storeImge(path+headPortraitUrl, headPortrait);
		UserInfo userInfo = userInfoDao.findOne(userId);
	    headPortraitUrl += filePath;
		userInfo.setHeadPortrait(headPortraitUrl);
		userInfoDao.save(userInfo);
		return headPortraitUrl;
	}

}
